let express = require("express");
let router = express.Router();
let jwt = require("jsonwebtoken");
let config = require("../libs/config");
let userModel = require("../model/user_login");

router.post("/api/v1/login", async function (req, res) {
  try {
    console.log(req.body.phone);
    let findUser = await userModel.find({
      phone: req.body.phone
    }).populate('department').exec();
    console.log(findUser);
    if (findUser.length > 0) {
      if (findUser[0].password == req.body.password) {
        if (findUser[0].audit) {
          if (findUser[0].studus == "已删除") {
            res.json({
              code: 203,
              mess: "该账号当前已被封禁，请联系管理员"
            });
          }
          let token = jwt.sign({
              _id: findUser._id
            },
            config.secretOrPrivateKey, {
              expiresIn: "1 days"
            }
          );
          res.json({
            code: 200,
            data: findUser,
            token
          });
        } else {
          res.json({
            code: 201,
            mess: "该账户未审核通过"
          });
        }
      } else {
        res.json({
          code: 202,
          mess: "密码错误"
        });
      }
    } else {
      res.json({
        code: 204,
        mess: "该账号不存在"
      });
    }
  } catch (error) {
    res.status(500).send(error);
  }
});

module.exports = router;
